package com.aliwo.algorithm.easy;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 给定一个数组和一个目标和，从数组中找两个数字相加等于目标和，输出这两个数字的下标.
 * nums=[2,9,1,7], targer = 10
 * return [1,2]
 *
 * @author Xu Yayuan
 * @date 2022/3/8
 */
public class TargetSum {
    public static void main(String[] args) {
        int[] nums = {2, 10, 8, 7, 6};
        int[] result = targetSum(nums, 15);
        Arrays.stream(result).forEach(System.out::println);
    }

    public static int[] targetSum(int[] nums, int target) {
        // 定义一个map key存储值，value存储数据下标
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) { // 循环遍历数组
            int sub = target - nums[i]; // 目标和减去当前值
            if (map.containsKey(sub)) {
                return new int[]{i, map.get(sub)};
            }
            // key是数组中的值，value是数组的下标
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}
